﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace EventLogAnalyzer.ViewModel
{
    public class LogDistributionListViewModel
    {
        public event ShowLogDetailsEventHandler ShowLogDetailsRequest;

        public LogDistributionListViewModel()
        {
            LogDistributionViewModel = new ObservableCollection<LogDistributionViewModel>();    
        }

        public void AddLogDistribution(IEnumerable<EventLogViewModel> filteredLogs)
        {
            var logDistributionViewModel = new LogDistributionViewModel(filteredLogs){Order = LogDistributionViewModel.Count};
            logDistributionViewModel.ShowLogGroupDetailsRequest += logDistributionViewModel_ShowLogGroupDetailsRequest;
            logDistributionViewModel.Selected += logDistributionViewModel_Selected;
            LogDistributionViewModel.ToList().ForEach(l => l.IsInFocus = false);
            LogDistributionViewModel.Add(logDistributionViewModel);
        }

        void logDistributionViewModel_Selected(object sender, SelectedEventHandlerArgs args)
        {
            var indexOfCurrentLogDist = LogDistributionViewModel.IndexOf((LogDistributionViewModel)sender);
            for (int i = indexOfCurrentLogDist + 1; i < LogDistributionViewModel.Count; )
                LogDistributionViewModel.RemoveAt(i);

            var remaining = LogDistributionViewModel.ToList().FindAll(l => l != sender);
            remaining.ForEach(x => x.IsInFocus = false);
        }

        void logDistributionViewModel_ShowLogGroupDetailsRequest(object sender, ShowLogGroupDetailsEventHandlerArgs args)
        {
            if (args.DrillDown)
            {
                var logDistributionViewModel = (LogDistributionViewModel) sender;
                var indexOfCurrentLogDist = LogDistributionViewModel.IndexOf(logDistributionViewModel);
                for (int i = indexOfCurrentLogDist + 1; i < LogDistributionViewModel.Count;)
                    LogDistributionViewModel.RemoveAt(i);
                AddLogDistribution(args.FilteredLogs);
            }
            if(ShowLogDetailsRequest != null)
                ShowLogDetailsRequest(this, new ShowLogDetailsEventHandlerArgs{Logs = args.FilteredLogs});
        }

        public ObservableCollection<LogDistributionViewModel> LogDistributionViewModel { get; set; }
    }
}